import type { App } from 'vue';

import { createApp } from 'vue';

import SmartUploader from './index.vue';

/**
 * 上传插件
 * @description 创建上传组件并挂载到body上
 * @Example:注册上传插件
 * import UploaderPlugin from '#/components/file-upload/use-global-uploader';
 * app.use(UploaderPlugin);
 * @Example：方式1
 * $uploader.show({ from: 业务类别, service: 服务类别, p1:xxx });
 * @Example：方式2
 * import { inject } from 'vue';
 * const uploader = inject('uploader');
 * uploader.show({ from: 业务类别, service: 服务类别 });
 */
class UploaderPlugin {
    private static instance: any = null;
    private app: App | null = null;
    private componentInstance: any = null; // 保存组件实例

    static getInstance() {
        if (!this.instance) {
            this.instance = new UploaderPlugin();
            this.instance.initialize();
        }
        return this.instance;
    }

    /**
     * 清理资源
     */
    destroy() {
        if (this.app) {
            this.app.unmount();
            this.app = null;
            this.componentInstance = null;
        }
    }

    /**
     * 初始化
     */
    initialize() {
        const container = document.createElement('div');
        document.body.append(container);

        // 创建应用实例并保存组件实例的引用
        this.app = createApp(SmartUploader, {});

        // 挂载并获取组件实例
        this.componentInstance = this.app.mount(container);
    }

    /**
     * 显示上传组件
     * @param params 上传参数
     */
    show(params: { from: string; service: string }) {
        // 触发显示逻辑
        if (this.componentInstance && this.componentInstance.show) {
            // 调用组件暴露的show方法
            this.componentInstance.show(params);
        } else {
            console.error('Uploader component instance not found or show method not available');
        }
    }
}

// 显示上传对话框
/* this.$uploader.show({ folderId: 123, userId: 456 });*/

// 或者通过注入使用
/* import { inject } from 'vue';
const uploader = inject('uploader');
uploader.show({ folderId: 123 });*/

// 全局安装
export default {
    install(app: App) {
        const uploader = UploaderPlugin.getInstance();
        app.config.globalProperties.$uploader = uploader;
        app.provide('uploader', uploader);
    },
};
